package com.zd.lib.http.okhttp;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * Created by zoudong on 16/6/14.
 */
public class ProgressRequestBody extends RequestBody {
    protected final RequestBody delegate;
    private final ProgressListener progressListener;
    //包装完成的BufferedSink
    private BufferedSink bufferedSink;
    public ProgressRequestBody(RequestBody responseBody, ProgressListener progressListener) {
        this.delegate = responseBody;
        this.progressListener = progressListener;
    }

    @Override
    public MediaType contentType() {
        return delegate.contentType();
    }

    @Override public long contentLength() {
        try {
            return delegate.contentLength();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }
    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (null==bufferedSink) {
             bufferedSink = Okio.buffer(new CountingSink(sink));
        }
        delegate.writeTo(bufferedSink);
        //必须调用flush，否则最后一部分数据可能不会被写入
        bufferedSink.flush();
    }

    protected final class CountingSink extends ForwardingSink {

        private long bytesWritten = 0;

        public CountingSink(Sink delegate) {
            super(delegate);
        }

        @Override public void write(Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);

            bytesWritten += byteCount;
        progressListener.onRequestProgress(bytesWritten, contentLength());
    }
    }
}